package com.hoshiicloud.saleorder.service.impl.refund;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.constant.refund.RefundOrderStatusEnum;
import com.hoshiicloud.common.constant.refund.RefundServiceTypeEnum;
import com.hoshiicloud.common.constant.refund.RefundTypeEnum;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.common.utils.SMSCodeUtil;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.entity.RefundOrder;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.OrderMainMapper;
import com.hoshiicloud.saleorder.mapper.refund.RefundOrderMapper;
import com.hoshiicloud.saleorder.service.refund.RefundOrderService;
import com.hoshiicloud.saleorder.vo.refund.RefundOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 退款单(RefundOrder)表服务实现类
 *
 * @author qry
 * @since 2019-08-22 11:00:16
 */
@Slf4j
@Service
public class RefundOrderServiceImpl extends ServiceImpl<RefundOrderMapper, RefundOrder> implements RefundOrderService {
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private OrderMainMapper orderMainMapper;

    @Override
    @Logable(authName = "前台用户操作-退款管理-获取退款单分页信息")
    @Cacheable(cacheNames = "RefundOrder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<RefundOrderVo> getPage(Page<RefundOrder> page, QueryWrapper<RefundOrder> queryWrapper, String key) {
        baseMapper.selectPage(page,queryWrapper);
        Page<RefundOrderVo> page2 = new Page<>(page.getCurrent(), page.getSize());
        page2.setTotal(page.getTotal());
        List<RefundOrderVo> list = new ArrayList<>();
        page.getRecords().stream().forEach(s->{
            RefundOrderVo vo;
            try {
                vo = BeanUtils.covertType(s, RefundOrderVo.class);
            } catch (Exception e) {
                log.error("分页查询退款单出参转换Bean异常",e);
                throw new ServiceException("分页查询退款单出参转换Bean异常");
            }
            vo.setServiceTypeCn(RefundServiceTypeEnum.getRefundServiceType(vo.getServiceType()));
            vo.setRefundTypeCn(RefundTypeEnum.getRefundTypeType(vo.getRefundType()));
            vo.setStatusCn(RefundOrderStatusEnum.getStatusCn(vo.getStatus()));
            list.add(vo);
        });
        page2.setRecords(list);
        return page2;
    }


    @Override
    @CacheEvict(cacheNames = {"RefundOrder"}, allEntries = true)
    @Logable(authName = "前台用户操作-退款管理-新增退款单")
    public RefundOrder saveRefundOrder(RefundOrder entity) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String t =  now.format(formatter);
        entity.setCreatedTime(now);
        entity .setUpdatedTime(now);
        entity .setId(this.getNewId());
        entity.setRefundNo(entity.getServiceType().toString()+entity.getRefundType().toString()+t+ SMSCodeUtil.getRandom(5));
        int i = baseMapper.insert(entity);
        if(i == 0){
            throw new ServiceException("生成退款单失败，请重试");
        }
        return entity;
    }

    @Override
    @CacheEvict(cacheNames = {"RefundOrder"}, allEntries = true)
    @Logable(authName = "前台用户操作-退款管理-修改退款单")
    public Boolean updateRefundOrder(RefundOrder entity) {
        RefundOrder oldOrder = baseMapper.selectById(entity.getId());
        if(null == oldOrder){
            throw new ServiceException("未获取到该退款单");
        }
        int oldStatus = oldOrder.getStatus();
        int serviceType = oldOrder.getServiceType();
        OrderMain orderMain= orderMainMapper.selectById(oldOrder.getMainId());
        if(null == orderMain){
            throw new ServiceException("未获取到该退款单的主订单信息");
        }

        if( oldStatus ==RefundOrderStatusEnum.REFUND_CANCEL.getCode()){
            throw new ServiceException("退款单已取消！无法进行其他操作,请刷新页面");
        }
        if( oldStatus ==RefundOrderStatusEnum.REFUND_SUCCESS.getCode()){
            throw new ServiceException("退款单已退款成功！无法进行其他操作,请刷新页面");
        }

        //数据库为已拒绝状态  只接受重新申请操作 或者取消
        if(oldStatus == RefundOrderStatusEnum.SELLER_REFUSE_REFUND.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.REFUND_CANCEL.getCode()){
            throw new ServiceException("退款单已被商家拒绝！请刷新页面!");
        }
        //数据库为等待商家付款  只接受银行处理中状态
        if(oldStatus == RefundOrderStatusEnum.WAIT_SELLER_PAY.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.BANK_PROCESSING.getCode()){
            throw new ServiceException("退款单当前状态等待商家打款！无法进行其他操作,请刷新页面");
        }
        //数据库为等待商家收货  只接受等待商家付款状态
        if(oldStatus == RefundOrderStatusEnum.WAIT_SELLER_RECEIVE.getCode() &&
                entity.getStatus().intValue() != RefundOrderStatusEnum.WAIT_SELLER_PAY.getCode()){
            throw new ServiceException("退款单当前状态等待商家收货！无法进行其他操作,请刷新页面");
        }
        //数据库为等待买家发货 只接受等待商家收货/取消 状态
        if(oldStatus == RefundOrderStatusEnum.WAIT_BUYER_DELIVERY.getCode()
              && entity.getStatus().intValue() != RefundOrderStatusEnum.WAIT_SELLER_RECEIVE.getCode()
              && entity.getStatus().intValue() != RefundOrderStatusEnum.REFUND_CANCEL.getCode()
            ){
            throw new ServiceException("退款单当前状态等待买家发货！无法进行其他操作,请刷新页面");
        }
        //数据库为等待商家处理 且退款单类型为仅退款 只接收等待商家付款/取消/拒绝 状态
        if(oldStatus == RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode()
                && serviceType == RefundServiceTypeEnum.ONLY_REFUND.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.WAIT_SELLER_PAY.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.REFUND_CANCEL.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.SELLER_REFUSE_REFUND.getCode()

        ){
            throw new ServiceException("退款单当前状态等待商家处理！无法进行付款/取消/拒绝 以外的操作,请刷新页面");
        }
        //数据库为等待商家处理 且退款单类型为退货退款 且主订单类型不为自提订单 只接收等待买家发货/取消/拒绝 状态
        if(oldStatus == RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode()
                && serviceType == RefundServiceTypeEnum.REFUND_RETURN_GOODS.getCode()
                && orderMain.getShippingId().longValue() != 3L
                && entity.getStatus().intValue() != RefundOrderStatusEnum.WAIT_BUYER_DELIVERY.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.REFUND_CANCEL.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.SELLER_REFUSE_REFUND.getCode()
        ){
            throw new ServiceException("退款单当前状态等待商家处理！无法进行其他操作,请刷新页面");
        }
        //数据库为等待商家处理 且退款单类型为退货退款 且主订单类型为自提订单 只接收等待商家收货/取消/拒绝 状态
        if(oldStatus == RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode()
                && serviceType == RefundServiceTypeEnum.REFUND_RETURN_GOODS.getCode()
                && orderMain.getShippingId().longValue() == 3L
                && entity.getStatus().intValue() != RefundOrderStatusEnum.WAIT_SELLER_RECEIVE.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.REFUND_CANCEL.getCode()
                && entity.getStatus().intValue() != RefundOrderStatusEnum.SELLER_REFUSE_REFUND.getCode()
        ){
            throw new ServiceException("退款单当前状态等待商家处理！无法进行其他操作,请刷新页面");
        }

        //数据库为 银行处理中 只接收退款成功状态
        if(oldStatus == RefundOrderStatusEnum.BANK_PROCESSING.getCode()
              && entity.getStatus().intValue() != RefundOrderStatusEnum.REFUND_SUCCESS.getCode()
        ){
            throw new ServiceException("退款单当前状态银行处理中！无法进行其他操作,请刷新页面");
        }

        entity.setUpdatedTime(LocalDateTime.now());
        int i = baseMapper.updateById(entity);
        if(i == 0){
            throw new ServiceException("编辑退款单失败，请重试");
        }
        return true;
    }

    @Override
    @Logable(authName = "退款管理-退款单表操作-根据ID查询退款单信息")
    @Cacheable(cacheNames = "RefundOrder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    public RefundOrder getRefundOrderById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    @Logable(authName = "退款管理-退款单表操作-根据条件查询退款单信息")
    @Cacheable(cacheNames = "RefundOrder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public List<RefundOrderVo> listRefundOrder(QueryWrapper<RefundOrder> q, String key) {
        List<RefundOrder> list2 = baseMapper.selectList(q);
        List<RefundOrderVo> list = new ArrayList<>();
        list2.stream().forEach(s->{
            RefundOrderVo vo;
            try {
                vo = BeanUtils.covertType(s, RefundOrderVo.class);
            } catch (Exception e) {
                log.error("分页查询退款单出参转换Bean异常",e);
                throw new ServiceException("分页查询退款单出参转换Bean异常");
            }
            vo.setServiceTypeCn(RefundServiceTypeEnum.getRefundServiceType(vo.getServiceType()));
            vo.setRefundTypeCn(RefundTypeEnum.getRefundTypeType(vo.getRefundType()));
            vo.setStatusCn(RefundOrderStatusEnum.getStatusCn(vo.getStatus()));
            list.add(vo);
        });
        return list;
    }

    @Override
    @CacheEvict(cacheNames = {"RefundOrder"}, allEntries = true)
    @Logable(authName = "前台用户操作-退款管理-修改退款单状态byParam")
    public Boolean updateByParam(OmnipotentParam<RefundOrder> param) {
        UpdateWrapper<RefundOrder> q = new OmnipotentWrapper().getUpdateWrapper(param.getWrappers());
        try{
            baseMapper.update(param.getEntity(),q);
        }catch (Exception e){
            log.error("前台用户操作-退款管理-修改退款单状态byParam:",e);
            throw new ServiceException("前台用户操作-退款管理-修改退款单状态byParam:"+ e.getMessage());
        }
        return true;
    }


    private Long getNewId(){
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("主键ID生成失败"));
        }
        return Long.valueOf(id);
    }


    /**
     * 根据自定义条件查询退款单信息
     */
    @Override
    @Cacheable(cacheNames = "RefundOrder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "前台用户操作-退款管理-根据任意条件查询退款单信息")
    public List<RefundOrder> omniRefundOrder(List<OmnipotentWrapper> wrappers, String key) {
        OmnipotentWrapper<RefundOrder> omnipotentWrapper = new OmnipotentWrapper();
        QueryWrapper<RefundOrder> wrapper = omnipotentWrapper.getWrapper(wrappers);
        return baseMapper.selectList(wrapper);
    }
}
